#pragma once

#include <iostream>
#include <unordered_map>
#include <string>
#include <fstream>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogModule;
using namespace InetAddrModule;
std::string defaultdictpath = "./dictionary.txt";
std::string sep = ": ";

class Dict
{
public:
    Dict(const std::string &path = defaultdictpath) : _dict_path(path)
    {
    }

    bool LoadDict()
    {
        std::ifstream in(_dict_path);
        if (!in.is_open())
        {
            LOG(LogLevel::DEBUG) << "打开字典：" << _dict_path << " 错误";
            return false;
        }
        std::string line;
        while (std::getline(in, line))
        {
            //"apple: 苹果"
            size_t pos = line.find(sep);
            if (pos == std::string::npos)
            {
                LOG(LogLevel::WARNING) << "解析： " << line << "失败！";
                continue;
            }
            std::string English = line.substr(0, pos);
            std::string Chinese = line.substr(pos + sep.size());
            if (English.empty() || Chinese.empty())
            {
                LOG(LogLevel::WARNING) << "没有有效内容: " << line;
                continue;
            }
            _dict.insert({English, Chinese});
            LOG(LogLevel::DEBUG) << "加载: " << line;
        }
        in.close();
        return true;
    }
    
    //翻译接口
    std::string Translate(const std::string& word, InetAddr& client)
    {
        auto it = _dict.find(word);
        if(it == _dict.end())
        {
            LOG(LogLevel::DEBUG) << "进入到了翻译模块, [" << client.IP() << " : " << client.Port() << "]# " << word << "->None";
            return "None";
        }
         LOG(LogLevel::DEBUG) << "进入到了翻译模块, [" << client.IP() << " : " << client.Port() << "]# " << word << "->" << it.operator->()->second;
         return it.operator->()->second;
    }

    ~Dict()
    {
    }

private:
    std::string _dict_path; // 路径+文件名
    std::unordered_map<std::string, std::string> _dict;
};